<template>
  <div id="app">
    <iframe
      id="aliyunPreview"
      src="https://preview.imm.aliyun.com/index.html"
      allowfullscreen
      frameborder="0"
      scrolling="no"
    ></iframe>
    <div class="w2-scale">
      <el-input-number
        v-model="num"
        :min="min"
        :max="max"
        size="mini"
        label="第几页"
        controls-position="right"
      ></el-input-number>
    </div>
  </div>
</template>

<script>
import { asyncossupload, asyncInquireusertotpdataid } from "../plugins/api.js";
import { mapActions } from "vuex";
import { GetQueryString } from "../plugins/utils";
import { throttle } from "underscore";
export default {
  name: "app",
  data() {
    return {
      min: 1,
      max: 10,
      num: 1,
      maxinx: 10
    };
  },
  async beforeMount() {
    let x;
    try {
      x = await this.session();
      if (!x) {
        location.href = "/";
      }
    } catch (e) {
      location.href = "/";
    }
  },
  async mounted() {
    window.sendMessage = (action, data) => {
      const test = document.getElementById("aliyunPreview");
      test.contentWindow.postMessage(
        this.json2str({
          action: action,
          data: data
        }),
        "*"
      );
    };

    window.addEventListener(
      "message",
      e => {
        let res;
        if (e.data && typeof e.data === "string") {
          res = JSON.parse(e.data);
          switch (res.action) {
            case "preview.ready":
              this.init();
              break;
            case "preview.meta":
              this.meta(res.data);
              break;
            case "message.error":
              break;
            case "logic.refreshToken":
              window.sendMessage("logic.setToken", this.setToken());
          }
        }
      },
      false
    );
  },
  watch: {
    num(v) {
      window.sendMessage("logic.toPage", {
        pageIndex: v // 跳转页码，从0开始
      });
    }
  },
  methods: {
    ...mapActions(["session"]),
    async init() {
      this.maxinx--;
      if (this.maxinx === 0) {
        this.$message("加载失败");
        return;
      }
      if (!this.url) {
        try {
          const ID = GetQueryString("ID");
          const arr = await asyncInquireusertotpdataid({ tpdata_ID: ID });
          this.url = arr.fileurl;
          const {
            accessKeyId,
            accessKeySecret,
            securityToken,
            expiration
          } = await asyncossupload();
          this.accessKeyId = accessKeyId;
          this.accessKeySecret = accessKeySecret;
          this.securityToken = securityToken;
          this.expiration = expiration;
        } catch (err) {
          this.$message({
            message: "没有权限哦！",
            type: "success"
          });
        }
      }
      window.sendMessage("preview.init", {
        url: this.url,
        region: "oss-cn-beijing",
        bucket: "hterobot-pdf",
        accessKeyId: this.accessKeyId,
        accessKeySecret: this.accessKeySecret,
        stsToken: this.securityToken,
        expires: 3600
      });
    },
    async setToken() {
      const upload = throttle(asyncossupload, 350000, { leading: true, trailing: false });
      const data = await upload();
      if (data) {
        this.accessKeyId = data.accessKeyId;
        this.accessKeySecret = data.accessKeySecret;
        this.stsToken = data.stsToken;
      }
      console.log(data);
      return {
        region: "oss-cn-beijing",
        accessKeyId: this.accessKeyId,
        accessKeySecret: this.accessKeySecret,
        stsToken: this.securityToken,
        bucket: "hterobot-pdf"
      };
    },
    json2str(obj) {
      return JSON.stringify(obj, function(key, val) {
        if (typeof val === "function") {
          val = val.toString();
        }
        return val;
      });
    },
    parse(params) {
      return Object.keys(params)
        .map(key => {
          return `${key}=${encodeURIComponent(params[key])}`;
        })
        .join("&");
    },
    meta(data) {
      this.max = data.pc;
      console.log("meta");
      window.sendMessage("setConfig", {
        writerCustomStyle: function(isMobile) {
          if (!isMobile) {
            return {
              // 页与页之间的距离
              pageSpacing: 20,
              // 每页的阴影样式
              pageShadow: "0px 0px 6px 0px rgba(0, 0, 0, 0.3)"
            };
          } else {
            return {
              pageBorder: "1px solid #d2d5d8"
            };
          }
        }
      });
      // 演示预览自定义样式
      window.sendMessage("setConfig", {
        powerpointCustomStyle: function(isMobile) {
          if (!isMobile) {
            return {
              // 隐藏翻页按钮
              paginationDisplay: false,
              // 隐藏全屏按钮
              fullScreenButtonDisplay: false
            };
          } else {
            return {};
          }
        }
      });
    }
  }
};
</script>


<style>
.w2-scale {
  color: #999;
  right: 60px;
  position: fixed;
  bottom: 67px;
  text-align: center;
  line-height: normal;
  transition: opacity 1s;
  opacity: 0.4;
  z-index: 199;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
.w2-scale:hover {
  opacity: 1;
}
#app .el-input-number--mini {
  width: 95px;
}
</style>

